import userApi from '@/api/user'
import store from 'store'
import cookies from 'js-cookie'

export default ({
	namespaced: true,
	state: () => {
		return {
			token: '',
			userInfo: store.get('userInfo'),
			loading: false,
			showLoginPop: false,
		}
	},
	mutations: {
		setUserInfo(state, data) {
			state.userInfo = data
			store.set('userInfo', data)
		},
		setToken(state, data) {
			state.token = data
			cookies.set('token', data)
		},
		setShowLoginPop(state, data) {
			state.showLoginPop = data
		},
		logOut(state,data) {
			store.remove('userInfo');
			state.userInfo = store.get('userInfo');
			cookies.remove("token");
			data.onSuccess && data.onSuccess();
		}
	},
	actions: {
		/**
		 * 用户登录
		 * @param {*} param0 mobile 账户名
		 * @param {*} param1 password 登录密码
		 * @param { Function } param2 登录成功后回调 onSuccess
		 */
		login({
			commit
		}, {
			mobile,
			password,
			onSuccess
		}){
			if (this.loading) {
				return
			}
			userApi.login({
				mobile,
				password
			}).then(res=>{
				console.log(res);
				commit('setToken', res.token);
				commit('setUserInfo', res);
				onSuccess && onSuccess();
				this.loading = false
			})
		},
		/**
		 * 用户注册
		 * @param {*} param0 mobile 账户名
		 * @param {*} param1 password 登录密码
		 */
		register({
			commit
		}, {
			mobile,
			password,
			onSuccess
		}){
			if (this.loading) {
				return
			}
			userApi.register ({
				mobile,
				password
			}).then(res=>{
				console.log(res);
				commit('setToken', res.token);
				commit('setUserInfo', res);
				onSuccess && onSuccess();
				this.loading = false
			})
		},
		/**
		 * 用户登出
		 * @param {*} param1 登出回调
		 */
		async logOut({
			commit
		}, {
			onSuccess
		}) {
			commit('logout');
			onSuccess && onSuccess()
		},
		// 展示登录弹窗
		showLoginPop({commit}) {
			commit('setShowLoginPop', true)
		},

		// 关闭登录弹窗
		closeLoginPop({commit}) {
			commit('setShowLoginPop', false)
		},

	}
})
